package org.ligson.springboot.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@Slf4j
public class RedisController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/api/redis/keys2")
    public void test() {
        List<String> keys = RedisUtils.scanKeys(stringRedisTemplate, "crux*");
        System.out.println(keys);

        for (String key : keys) {
            if (key.contains("querycache")) {
                String value = stringRedisTemplate.boundValueOps(key).get();
                System.out.println(value);
            }
        }
    }


    @GetMapping("/api/redis/test2")
    public void test2() {
        String keyOfKeySet = "test";
//        String scripts = "" +
//                //"local keyOfKeySet = KEYS[1]\n" +
//                "local keySet = redis.call(\"hkeys\",KEYS[1])\n" +
//                "redis.call(\"del\",unpack(keySet))\n" +
//                "redis.call(\"del\",KEYS[1])";
        byte[] buffer = "abc".getBytes(StandardCharsets.UTF_8);
        System.out.println(Arrays.toString(buffer));


        String scripts = "redis.call('set',KEYS[1],unpack({97,98,99}))";
        RedisScript<Object> rs = RedisScript.of(scripts);

        stringRedisTemplate.execute(rs, Arrays.asList("test"), buffer);

        log.debug(stringRedisTemplate.boundValueOps("test").get());
//        stringRedisTemplate.execute((RedisCallback<Object>) connection -> {
//            ///List<byte[]> args = Arrays.asList(keyOfKeySet.getBytes(StandardCharsets.UTF_8));
//            connection.eval(scripts.getBytes(StandardCharsets.UTF_8), ReturnType.INTEGER, 0, keyOfKeySet.getBytes(StandardCharsets.UTF_8));
//            return null;
//        });
    }

    @GetMapping("/api/redis/set")
    public void setkey(String key, String value) {
        stringRedisTemplate.boundValueOps(key).set(value);
    }

    @GetMapping("/api/redis/get")
    public String getkey(String key) {
        return stringRedisTemplate.boundValueOps(key).get();
    }

    @GetMapping("/api/redis/keys")
    public Map<String, String> keys(String key) {
        Set<String> keys = stringRedisTemplate.keys(key);
        Map<String, String> v = new HashMap<>();
        assert keys != null;
        keys.forEach(k -> v.put(k, stringRedisTemplate.boundValueOps(k).get()));
        return v;
    }
}
